package com.example.demo.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Controller
public class DownloadController {

    @RequestMapping("/download")
    public String toDownload(){
        return "download";
    }

    @PostMapping("/getFileDataList")
    @ResponseBody
    public Map<String,Object> getFileDataList(){
        Map<String,Object> resultMap = new HashMap<>();

        List<Map<String,Object>> dataList = new LinkedList<>();
        File rootFile = new File(FileConfig.downloadPath);
        if(rootFile.exists()){
            File[] files = rootFile.listFiles();
            for(int i=0;i< files.length;i++){
                Map<String,Object> fileMap = new HashMap<>();
                if(files[i].isFile()){
                    fileMap.put("path",files[i].getAbsoluteFile());
                    fileMap.put("name",files[i].getName());
                    dataList.add(fileMap);
                }else{
                    fileMap.put("path",files[i].getAbsoluteFile());
                    fileMap.put("name",files[i].getName());
                }
            }
        }
        resultMap.put("code","0");
        resultMap.put("msg","");
        resultMap.put("count",dataList.size());
        resultMap.put("data",dataList);
        return resultMap;
    }
    @PostMapping("/downFile")
    @ResponseBody
    public void downFile(HttpServletRequest request, HttpServletResponse response){
        try {

            String filePath = request.getParameter("filePath");
            File file = new File(filePath);
            InputStream in = new FileInputStream(file);
            String fileName= file.getName();
            fileName= URLEncoder.encode(fileName,"UTF-8");

            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/x-download;charset=utf-8");

            OutputStream out = response.getOutputStream();
            IOUtils.copy(in, out);

            out.flush();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
